package Thread;

import java.util.Scanner;

public class Demo12 {

    private static volatile int n = 0;

    public static void main2(String[] args) {
        Thread t1 = new Thread(() -> {
           while(n == 0){
               //这里面什么都不写
           }
            System.out.println(" t1 线程结束循环");
        });

        Thread t2 = new Thread(() -> {
            Scanner scan = new Scanner(System.in);
            System.out.println("请输入一个整数：");
            n = scan.nextInt();
        });

        t1.start();
        t2.start();
    }

    //此时运行代码会发现程序进入了死循环
    //这是因为编译器自动优化：针对“读取 n 内存“数据的优化操作
    //让 while(n == 0) 这里我们对变量 n 的改变 “不可见”

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            while(n == 0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(" t1 线程结束循环");
        });

        Thread t2 = new Thread(() -> {
            Scanner scan = new Scanner(System.in);
            System.out.println("请输入一个整数：");
            n = scan.nextInt();
        });

        t1.start();
        t2.start();
    }


    //volatile 关键字修饰一个变量，提示编译器，这个变量是“易变”的
    //编译器就不会对这个变量优化
    public static void main1(String[] args) {
        Thread t1 = new Thread(() -> {
            while(n == 0){
                //这里面什么都不写
            }
            System.out.println(" t1 线程结束循环");
        });

        Thread t2 = new Thread(() -> {
            Scanner scan = new Scanner(System.in);
            System.out.println("请输入一个整数：");
            n = scan.nextInt();
        });

        t1.start();
        t2.start();
    }

}
